//
//  GMRegisterInfoViewController.m
//  GuardMan
//
//  Created by steven on 2016/12/25.
//  Copyright © 2016年 steven. All rights reserved.
//

#import "GMRegisterInfoViewController.h"
#import "GMNavigationController.h"
#import "GMRegisterInfoDataController.h"
#import "GMAuthView.h"
#import "GMButton.h"
#import "GMAuthTextField.h"
#import "GMDebtorListViewController.h"
#import "GMMenuViewController.h"
#import <MMDrawerController/MMDrawerController.h>

@interface GMRegisterInfoViewController ()

@property (nonatomic, strong)GMAuthView *authView;
@property (nonatomic, strong)GMRegisterInfoDataController *registerInfoDataController;

@property (nonatomic, strong)NSString *nickName;
@property (nonatomic, strong)NSString *firstPassword;
@property (nonatomic, strong)NSString *secondPassword;
@property (nonatomic, strong)NSString *recommend;

@end

@implementation GMRegisterInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.registerInfoDataController = [[GMRegisterInfoDataController alloc] init];
    
    [self setupContentView];
}

#pragma mark - set up main view
- (void)setupContentView {
    self.view.backgroundColor = [UIColor whiteColor];
    // set navigation title
    [self.navigationItem setTitle:@"注册"];
    
    // auth base view
    [self.view addSubview:self.authView];
    [self.authView autoPinEdgesToSuperviewEdges];
    
    // first password text field
    [self.authView addSubview:self.firstPasswdTextField];
    [self.firstPasswdTextField autoAlignAxisToSuperviewAxis:ALAxisVertical];
    [self.firstPasswdTextField autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.authView withOffset:-AUTH_TEXT_FIELD_HEIGHT];
    [self.firstPasswdTextField autoSetDimensionsToSize:CGSizeMake(self.view.frame.size.width*0.8,AUTH_TEXT_FIELD_HEIGHT)];
    
    // second password text field
    [self.authView addSubview:self.secondPasswordTextField];
    [self.secondPasswordTextField autoAlignAxisToSuperviewAxis:ALAxisVertical];
    [self.secondPasswordTextField autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.firstPasswdTextField withOffset:14];
    [self.secondPasswordTextField autoSetDimensionsToSize:CGSizeMake(self.view.frame.size.width*0.8, AUTH_TEXT_FIELD_HEIGHT)];

    // recommend text field
    [self.authView addSubview:self.recommendTextField];
    [self.recommendTextField autoAlignAxisToSuperviewAxis:ALAxisVertical];
    [self.recommendTextField autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.secondPasswordTextField withOffset:14];
    [self.recommendTextField autoSetDimensionsToSize:CGSizeMake(self.view.frame.size.width*0.8, AUTH_TEXT_FIELD_HEIGHT)];

    // nick name text field
    [self.authView addSubview:self.nickNameTextField];
    [self.nickNameTextField autoPinEdge:ALEdgeLeading toEdge:ALEdgeLeading ofView:self.firstPasswdTextField];
    [self.nickNameTextField autoPinEdge:ALEdgeBottom toEdge:ALEdgeTop ofView:self.firstPasswdTextField withOffset:-14];
    [self.nickNameTextField autoSetDimensionsToSize:CGSizeMake(self.view.frame.size.width*0.8, AUTH_TEXT_FIELD_HEIGHT)];
    
    // register button
    [self.authView addSubview:self.registerButton];
    [self.registerButton autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.recommendTextField withOffset:14];
    [self.registerButton autoAlignAxisToSuperviewAxis:ALAxisVertical];
    [self.registerButton autoSetDimensionsToSize:CGSizeMake(self.view.frame.size.width*0.8, AUTH_TEXT_FIELD_HEIGHT)];
}

#pragma mark - register button pressed
- (void)registerButtonPressed {
    if ([self checkInputValidate]) {
        // register now
        NSDictionary *params = @{@"name":self.nickName,
                                 @"phone_number":self.phoneNo,
                                 @"password":self.firstPassword,
                                 @"verifyCode":self.verificationCode,
                                 @"recommend_user":self.recommend};
        [self.registerInfoDataController registerWithParams:params callback:^(NSString *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (error == nil) {
                    NSLog(@"Register success");
                    [self renderView];
                } else {
                    NSLog(@"Register failed: %@", error);
                    [self showAlertMessage:error];
                }
            });
        }];
    }
}

#pragma mark - check validate
- (BOOL)checkInputValidate {
    [self.nickNameTextField resignFirstResponder];
    [self.firstPasswdTextField resignFirstResponder];
    [self.secondPasswordTextField resignFirstResponder];
    
    self.nickName = self.nickNameTextField.text;
    self.firstPassword = self.firstPasswdTextField.text;
    self.secondPassword = self.secondPasswordTextField.text;
    self.recommend = self.recommendTextField.text;
    
    if (self.nickName.length == 0) {
        [self showAlertMessage:@"请输入昵称"];
        return NO;
    } else if(self.firstPassword.length == 0) {
        [self showAlertMessage:@"请输入密码"];
        return NO;
    } else if(self.secondPassword.length == 0) {
        [self showAlertMessage:@"请输入确认密码"];
        return NO;
    } else if(self.firstPassword != self.secondPassword) {
        [self showAlertMessage:@"密码不一致"];
        return NO;
    }
    else {
        return YES;
    }
}

#pragma mark - render view
- (void)renderView {
    NSDictionary *dict = self.registerInfoDataController.response[@"data"];
    NSString *token = dict[@"token"];
    NSDictionary *userDict = dict[@"user"];
    NSString *userId = [userDict[@"id"] stringValue];
    NSString *name = userDict[@"name"];
    NSString *headImg = userDict[@"headImg"];
    NSString *type = userDict[@"type"];
    NSString *vip = userDict[@"vip"];
    NSString *mobile = userDict[@"account"];
    NSString *recommend = userDict[@"recommend"];

    NSLog(@"Login succeed\nid:%@\nname:%@\nToken:%@", userId, name, token);

    // store user info
    [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"userId"];
    [[NSUserDefaults standardUserDefaults] setObject:name forKey:@"name"];
    [[NSUserDefaults standardUserDefaults] setObject:headImg forKey:@"headImageUrl"];
    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] setObject:type forKey:@"type"];
    [[NSUserDefaults standardUserDefaults] setObject:vip forKey:@"vip"];
    [[NSUserDefaults standardUserDefaults] setObject:mobile forKey:@"mobile"];
    [[NSUserDefaults standardUserDefaults] setObject:recommend forKey:@"recommend"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    [self setupMainViewController];
}

#pragma mark - set up main viewController
- (void)setupMainViewController {
    GMDebtorListViewController *clientViewController = [[GMDebtorListViewController alloc] init];
    GMMenuViewController *menuViewController = [[GMMenuViewController alloc] init];

    GMNavigationController *centerNavigationVC = [[GMNavigationController alloc] initWithRootViewController:clientViewController];
    GMNavigationController *leftNavigationVC = [[GMNavigationController alloc] initWithRootViewController:menuViewController];

    MMDrawerController *drawerController = [[MMDrawerController alloc] initWithCenterViewController:centerNavigationVC leftDrawerViewController:leftNavigationVC];
    drawerController.openDrawerGestureModeMask = MMOpenDrawerGestureModeAll;
    drawerController.closeDrawerGestureModeMask = MMCloseDrawerGestureModeAll;

    drawerController.maximumLeftDrawerWidth = 200.0;

    [[[UIApplication sharedApplication] delegate] window].rootViewController = drawerController;
}

// Getter for authView
- (GMAuthView *)authView {
    if (!_authView) {
        _authView = [[GMAuthView alloc] init];
    }
    
    return _authView;
}


// Getter for nick name text field
- (GMAuthTextField *)nickNameTextField {
    if (!_nickNameTextField) {
        _nickNameTextField = [[GMAuthTextField alloc] init];
        _nickNameTextField.placeholder = @"公司或代表人姓名";
    }
    
    return _nickNameTextField;
}

// Getter for first passwrod text field
- (GMAuthTextField *)firstPasswdTextField {
    if (!_firstPasswdTextField) {
        _firstPasswdTextField = [[GMAuthTextField alloc] init];
        _firstPasswdTextField.secureTextEntry = YES;
        _firstPasswdTextField.placeholder = @"输入密码";
    }
    
    return _firstPasswdTextField;
}

// Getter for second passwrod text field
- (GMAuthTextField *)secondPasswordTextField {
    if (!_secondPasswordTextField) {
        _secondPasswordTextField = [[GMAuthTextField alloc] init];
        _secondPasswordTextField.secureTextEntry = YES;
        _secondPasswordTextField.placeholder = @"确认密码";
    }
    
    return _secondPasswordTextField;
}

// Getter for recommend text field
- (GMAuthTextField *)recommendTextField {
    if (!_recommendTextField) {
        _recommendTextField = [[GMAuthTextField alloc] init];
        _recommendTextField.keyboardType = UIKeyboardTypeNumberPad;
        _recommendTextField.placeholder = @"推荐码(可选)";
    }

    return _recommendTextField;
}

// Getter for register button
- (GMButton *)registerButton {
    if (!_registerButton) {
        _registerButton = [[GMButton alloc] init];
        _registerButton.titleLabel.font = [UIFont systemFontOfSize:AUTH_FONT_SIZE];
        [_registerButton setTitle:@"完成" forState:UIControlStateNormal];
        [_registerButton addTarget:self action:@selector(registerButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _registerButton;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
